package com.lly.schedule.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class JDBCUtil {
    private static DataSource dataSource;
    private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();

    static{
        Properties properties = new Properties();
        InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            properties.load(resourceAsStream);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            dataSource=DruidDataSourceFactory.createDataSource( properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConnection() throws Exception{
        Connection connection = threadLocal.get();
        if (connection ==null){
             connection = dataSource.getConnection();
            threadLocal.set(connection);
        }
        return connection;
    }
    public static void closeConnection() throws Exception{
        Connection connection = threadLocal.get();
        if (connection!=null){
            threadLocal.remove();
            connection.setAutoCommit(true);
            connection.close();
         }
    }
}
